package com.wangshb.upms.core.tree;

import lombok.*;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class TreeNode {

    private Long id = 0L;

    private String label = "根节点";

    private Long parentId = -1L;

    private String checked = "0";

    private Long version;

    private List<TreeNode> children = new ArrayList<>(0);


    public static TreeNode listToTree(List<TreeNode> list) {
       return listToTree(list, Collections.emptyList());
    }


    public static List<TreeNode> convertTree(final Long rootId, final Map<Long, List<TreeNode>> map, List<Long> defaultCheckedIdList) {
        List<TreeNode> treeNodes = map.get(rootId);

        if (CollectionUtils.isEmpty(treeNodes)) {
            return Collections.emptyList();
        }

        treeNodes.stream().forEach(treeNode -> {
            treeNode.setChecked(defaultCheckedIdList.contains(treeNode.getId()) ? "1" : "0");
            treeNode.getChildren().addAll(convertTree(treeNode.getId(), map, defaultCheckedIdList));
        });
        return treeNodes;
    }


    public static TreeNode listToTree(List<TreeNode> list, List<Long> defaultCheckedIdList)  {
        TreeNode rootTreeNode = new TreeNode();
        if (CollectionUtils.isEmpty(list)) {
            return rootTreeNode;
        }

        Map<Long, List<TreeNode>> map = new HashMap<>(10);
        list.stream().forEach(treeNode -> {
            if (!map.containsKey(treeNode.getParentId())) {
                map.put(treeNode.getParentId(), new ArrayList<>());
            }
            map.get(treeNode.getParentId()).add(treeNode);
        });

        rootTreeNode.setChildren(convertTree(rootTreeNode.getId(), map, defaultCheckedIdList != null ? defaultCheckedIdList : Collections.emptyList()));
        return rootTreeNode;
    }
}
